<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label=" 机构  "  prop="departmentId">
          <el-select v-model="listQuery.departmentId" @change="deptChange1" clearable placeholder="请选择">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="停车场">
          <el-select v-model="listQuery.parkId" placeholder="请选择" clearable style="width: 180px;">
            <el-option
              v-for="item in allParkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="规则名称">
          <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 180px;" placeholder="请输入"/>
        </el-form-item>

        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>

        <el-button class="filter-item" style="float:right" type="primary" icon="el-icon-plus" @click="startAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row >

      <el-table-column align="center" label="规则名称" prop="name"/>

      <el-table-column align="center" label="规则类型" prop="type">
        <template slot-scope="scope">
          <el-tag>{{ getType(scope.row.type) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否允许线上购买" prop="buyOnline">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.buyOnline===1?'是':'否' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="金额" prop="price"/>

      <el-table-column align="center" label="创建时间" prop="createTime"/>

      <el-table-column align="center" label="停车场" prop="parkName"/>

      <el-table-column align="center" label="所属机构" prop="departmentName"/>

      <el-table-column align="center" label="操作" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="startEditStaticRule(scope.row)">编辑</el-button>
          <!-- <el-button type="primary" size="small" @click="deleteStaticRule(scope.row.name, scope.row.id)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="dialogType == 1?'添加收费规则':'修改收费规则'" :visible.sync="dialogFormVisible" width="45%">
      <el-form ref="dialogForm" :inline="true" :rules="formRules" :model="dialogForm"  label-width="160px">
        <el-form-item label=" 机构  " prop="departmentId">
          <el-select v-model="dialogForm.departmentId" :disabled="dialogType === 2"
          placeholder="请选择" @change="deptChange">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label=" 停车场  " prop="parkId">
          <el-select v-model="dialogForm.parkId" :disabled="dialogType === 2" placeholder="请选择">
            <el-option
              v-for="item in parkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label=" 规则名称  " prop="name">
          <el-input v-model="dialogForm.name" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item>
        <el-form-item label=" 备注  ">
          <el-input v-model="dialogForm.remark" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item>
        <el-form-item label=" 类型  " prop="type">
          <el-select v-model="dialogForm.type" placeholder="请选择">
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"/>
          </el-select>
        </el-form-item>
        <el-form-item label=" 价格  " prop="price" >
          <el-input v-model="dialogForm.price" clearable class="filter-item" style="width: 100%;" placeholder=""/>
        </el-form-item>
        <el-form-item label=" 是否允许线上购买" prop="buyOnline" style="width: 45%;">
          <el-radio v-model="dialogForm.buyOnline" :label="1">是</el-radio>
          <el-radio v-model="dialogForm.buyOnline" :label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="绑定月卡附加规则" prop="feeRuleFlag" style="width: 45%;">
          <el-radio v-model="dialogForm.feeRuleFlag" :label="1">是</el-radio>
          <el-radio v-model="dialogForm.feeRuleFlag" :label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="月卡附加规则" v-if="dialogForm.feeRuleFlag == 1" prop="feeRuleId">
          <el-select v-model="dialogForm.feeRuleId"
          placeholder="请选择">
            <el-option
              v-for="item in fujiaRule"
              :key="item.id"
              :label="item.feeRuleName"
              :value="item.id"/>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="confirmEdit('dialogForm');">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, deleteParkStaticRule, createParkStaticRule, updateParkStaticRule,
listDepartmentRule,parkStaticRuleDetail } from '@/api/parkStaticRule'
import { getDepartmentList,getListAuthPark } from '@/api/base'
import { getData, } from '@/api/system/dictionary'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'StaticRule',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      typeList: [],
      listQuery: {
        page: 1,
        pageSize: 20
      },
      downloadLoading: false,
      dialogFormVisible: false,
      dialogForm: {},
      dialogType: 1,
      departmentList: [],
      parkList: [],
      allParkList: [],
      formRules: {
        departmentId: [{ required: true, message: '请选择机构', validator: this.checkSelected, trigger: 'change' }],
        parkId: [{ required: true, message: '请选择停车场', validator: this.checkSelected, trigger: 'change' }],
        name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', validator: this.checkSelected, trigger: 'change' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        feeRuleFlag: [{ required: true, message: '请选择是否绑定月卡附加规则', trigger: 'change' }],
        feeRuleId: [{ required: true, message: '请选择月卡附加规则',validator: this.checkSelected, trigger: 'change' }],
      },
      fujiaRule:[],//月卡附加规则数据
    }

  },
  created() {
    this.getDepartmentList()
    this.getList()
		this.getData()
  },
  methods: {
    getDepartmentList(){//获取机构
      getDepartmentList().then(res => {
        this.departmentList = res.data || []
      })
    },
    async getListAuthPark(departmentId){//获取停车场
      let res = await getListAuthPark({departmentId})
      return res.data || []
    },
		async getData(){//类型
			let res = await getData('EParkStaticRuleType')
			let list = res.data || []
			this.typeList = [...list]
		},
    async deptChange1(e){//机构下拉选择
      let listQuery = {...this.listQuery}
      listQuery.parkId = ''
      this.listQuery = {...listQuery}
      if(!e) return this.allParkList = []
      this.allParkList = await this.getListAuthPark(e)
    },
    listDepartmentRule(departmentId){//机构下的收费规则列表
      listDepartmentRule({
        departmentId,
        type: 3,
      }).then(res => {
        this.fujiaRule = res.data || []
      })
    },
    // 校验下拉框
    checkSelected(rule, value, callback) {
      if (!value) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    },

    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        let data = response.data || {}
        this.list = data.list || []
        this.total = data.total || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    getType(type) {
      if (type === 1) {
        return '包天'
      } else if (type === 2) {
        return '包月'
      } else if (type === 3) {
        return '包季度'
      } else if (type === 4) {
        return '年'
      }
      return '未知类型'
    },
    deleteStaticRule(name, parkId) {
      this.$confirm(`您确定删除商户：${name}`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteParkStaticRule({ id: parkId }).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    startAdd() {
      this.dialogForm = {}
      this.dialogFormVisible = true
      this.dialogType = 1
      this.parkList = []
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
      this.getDepartmentList()
    },
    confirmEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogType === 1) {
            createParkStaticRule(this.dialogForm).then(response => {
              this.$message({
                message: '添加成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          } else {
            updateParkStaticRule(this.dialogForm).then(response => {
              this.$message({
                message: '修改成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    startEditStaticRule(row) {
      parkStaticRuleDetail(row.id).then(async response => {
        let data = response.data || {}
        this.dialogFormVisible = true
        this.dialogType = 2
        this.dialogForm = {...data}
        this.listDepartmentRule(data.departmentId)
        this.$nextTick(() => {
          this.$refs.dialogForm.clearValidate()
        })
        this.parkList = []
        this.parkList = await this.getListAuthPark(this.dialogForm.departmentId)
        this.getDepartmentList()
      })

    },
    deptChange(event){
      let dialogForm = {...this.dialogForm}
      dialogForm.parkId = ''
      this.dialogForm = {...dialogForm}
      this.selectDepartmentId(event)
    },
    async selectDepartmentId(event) {
      console.log('event',event)
      this.listDepartmentRule(event)
      this.parkList = []
      this.parkList = await this.getListAuthPark(event)

    }


  }
}
</script>
